package com.station.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ObjectElementUtil {

	/**
	 * 获取对象getter方法属性名
	 *
	 * @param
	 */
	public static List<String> getPropertys(Object obj) {

		List<String> elementList = new ArrayList<String>();
		if (obj != null) {
			Class clazz = obj.getClass();
			try {
				Method[] methods = clazz.getDeclaredMethods();
				for (int i = 0; i < methods.length; i++) {
					if (methods[i].getName().startsWith("get")) {
						String _name = methods[i].getName().replace("get", "");
						// Object _value = methods[i].invoke(obj, null);
						elementList.add(_name); // 对象属性名
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.out.print("Object is null");
		}
		return elementList;
	}


	/**
	 * 获取属性名数组
	 * */
	public static String[] getFiledName(Object o) {
		Field[] fields = o.getClass().getDeclaredFields();
		String[] fieldNames = new String[fields.length];
		for (int i = 0; i < fields.length; i++) {
			// System.out.println(fields[i].getType());
			fieldNames[i] = fields[i].getName();
		}
		return fieldNames;
	}

	/**
	 * 根据属性名获取属性值
	 */
	public static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			return null;
		}
	}
}
